<?php

namespace App\Supports\Auth\Wechat;

use Exception;
use App\Models\User;
use EasyWeChat\OpenPlatform\Application;
use Illuminate\Validation\ValidationException;

class WechatAuth
{
	protected $wechat;
	
	protected $authData;
	protected $unionid;
	protected $openid;
	
	public function __construct()
	{
		$this->wechat = new Application(config('wechat.open_platform.default'));
	}
	
	protected function httpValidate()
	{
		if (request()->user()->isWeixinBound()) {
			throw ValidationException::withMessages(['code' => '微信已被其它账号绑定']);
		}
		
		request()->validate(['code' => 'required|string']);
		
		$code = request('code');
		
		try {
			$authData = $this->wechat->oauth->userFromCode($code);
			$this->setParams($authData);
			if ($this->isWechatBound()) {
				throw ValidationException::withMessages(['code' => '微信已被其它账号绑定']);
			}
		} catch (Exception $e) {
			throw ValidationException::withMessages(['code' => '参数错误，无法获取用户信息']);
		}
	}
	
	protected function setParams($authData)
	{
		$this->authData = $authData;
		$this->unionid = $authData->getRaw()['unionid'] ?? null;
		$this->openid = $authData->getId();
	}
	
	public function isWechatBound()
	{
		$oldUser = null;
		
		if ($this->unionid) {
			$oldUser = User::where('wx_unionid', $this->unionid)->first();
		} else {
			$oldUser = User::where('wx_openid', $this->openid)->first();
		}
		
		return $oldUser ? true : false;
	}
}
